package com.zly.gateway.predicate;

import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    private final String USER_KEY = "user";

    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return serverWebExchange -> {
            if (serverWebExchange.getRequest().getQueryParams().containsKey(USER_KEY)) {
                String user = serverWebExchange.getRequest().getQueryParams().getFirst(USER_KEY);
                return Objects.equals(user, config.getUser());
            }else {
                return false;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of(USER_KEY);
    }

    @Validated
    public static class Config {
        @Getter
        @Setter
        @NotBlank
        private String user;
    }
}
